const fs = require("fs");

const { sectionPath, includePath, readFile, writeFile,replaceComponentName, buildSectionPath, buildAssetsPath, buildSnippetPath } = require("../util");
const { buildThemeCss, buildThemejs,createThemeGlobal } = require("../service/block");

var checkDirectory = function (src) {
    let paths = fs.readdirSync(src); //同步读取当前目录
    paths.forEach(function (path) {
        var _src = src + "/" + path;
        fs.stat(_src, function (err, stats) {
            //stats  该对象 包含文件属性
            if (err) throw err;
            if (stats.isFile()) {
                readable.pipe(writable);
            } else if (stats.isDirectory()) {
                //是目录则 递归
                checkDirectory(_src, copy);
            }
        });
    });
};
// https://account-test.oemsaas.cn/login
// 获取所有的积木块
function getCardAll() {
    const dir = "./admin/app/view/sections";
    const sections = fs.readdirSync(dir);
    const sectionsAll = {};
    sections.forEach((file) => {
        if (file.indexOf(".liquid") == -1) {
            const cards = fs.readdirSync(dir + "/" + file);
            sectionsAll[file] = {};
            cards.forEach((cardFile) => {
                const stats = fs.statSync(`${dir}/${file}/${cardFile}`);
                if (stats.isDirectory()) {
                    var schema = JSON.parse(readFile(sectionPath(`${file}/${cardFile}`, "json"))).schema;
                    schema["router"] = `${file}:${cardFile}`;
                    sectionsAll[file][cardFile] = schema;
                } else {
                    console.log("文件错误", file + cardFile);
                }
            });
        }
    });

    return sectionsAll;
}


/**
 * @description: 识别Include引入的文件名称
 * @param {*} content 文本内容
 * @return {*}
 */
function getIncludeNames(content) {
    var pattern = /include\s+'([^']+)'/g;
    var matches = content.match(pattern);
    if (matches) {
        var includeStrings = matches.map(function (match) {
            return match.replace(/include\s+'([^']+)'/, "$1");
        });
        return includeStrings;
    } else {
        return [];
    }
}


/**
 * @description: 替换文件中的 Include 引入的文件名 多层级改成单层级
 * @param {*} content 内容
 * @param {*} snippetsPaths 需要替换的引入文件名集合
 * @return {*} 替换后的内容
 */
function replaceSnippetsFileName(content, snippetsPaths) {
    snippetsPaths.forEach((path) => {
        if (path.indexOf("/")) {
            const regExp = new RegExp(`({%.*?${path}.*?)%}`, 'g');
            content = content.replace(regExp,function(val,p1,offset,string){
                return  `${p1}, section_id:section_id %}`
            }).replace(path, path.replace("/", "_"));
        }
    });
    return content;
}

/**
 * @description:  递归循环引入代码片段的文件
 * @param {*} snippetsPaths 包含的代码片段文件路径
 * @param {*} themeConfig 模版配置文件
 * @return {*}
 */
function writeSnippetsFile(snippetsPaths, themeConfig) {
    snippetsPaths.forEach((path) => {
        var readContent = readFile(includePath(path, "liquid"));
        if (readContent) {
            const includeNames = getIncludeNames(readContent);
            const body = replaceComponentName(replaceSnippetsFileName(readContent, includeNames),path)
            writeFile(buildSnippetPath(themeConfig.name, path), body);
            if (includeNames.length) {
                writeSnippetsFile(includeNames, themeConfig);
            }
        }
    });
}

function setSchemaContent(card) {
    var schema = {};
    schema["tag"] = card["tag"];
    schema["name"] = card["name"];
    schema["max_blocks"] = card["max_blocks"];
    schema["class"] = card["class"];
    schema["settings"] = card["settings"];
    schema["blocks"] = card["blocks"];
    schema["default"] = card["default"];

    return `{% schema %}\n${JSON.stringify(schema,"", "\t")}\n{% endschema %}`
}

/**
 * @description: 更具选择积木块生成模版文件
 * @param {*} cardList 积木块列表
 * @return {*}
 */
function createThemeCardList(cardList, themeConfig) {
    return new Promise((resolve, reject) => {
        try {
            cardList.forEach((card) => {
                var router = card.router.replace(/\:/g, "/");
                var readContent = readFile(sectionPath(router, "liquid"));
                var writeCardFilePath = buildSectionPath(themeConfig.name, router);
                var includeNames = getIncludeNames(readContent);
                // 写入积木块文件
                writeFile(writeCardFilePath, replaceSnippetsFileName(readContent, includeNames) + '\n' + setSchemaContent(card));
                // 代码片段文件
                writeSnippetsFile(includeNames, themeConfig);
            });
            return resolve("积木块完成");
        } catch (error) {
            console.log(error,"文件写入错误");
            return reject("异常错误");
        }
    });
}

/**
 * @description: 获取所有用到文件路径
 * @param {*} cardList
 * @return {*}
 */
function getAllFilePath(cardList) {
    // var filePaths = [];
    let filePaths = new Set();
    function getSnippetsFileName(includeNames) {
        includeNames.forEach((path) => {
            filePaths.add(includePath(path, ""));
            var readContent = readFile(includePath(path, "liquid"));
            if (readContent) {
                const includeNames = getIncludeNames(readContent);
                if (includeNames.length) {
                    getSnippetsFileName(includeNames);
                }
            }
        });
    }

    cardList.forEach((card) => {
        var router = card.router.replace(/\:/g, "/");
        var readContent = readFile(sectionPath(router, "liquid"));
        var includeNames = getIncludeNames(readContent);
        filePaths.add(sectionPath(router, ""));
        if (includeNames.length) {
            getSnippetsFileName(includeNames);
        }
    });

    return filePaths;
}

/**
 * @description: 创建模版
 * @param {*} global 全局数据
 * @param {*} cardList 积木块列表
 * @param {*} theme 模版配置
 * @return {*}
 */
function createTheme({ global, cardList, themeConfig }) {
    if (!cardList) {
        return Promise.resolve({ code: 500, msg: "没有积木块" });
    }

    if (!global) {
        return Promise.resolve({ code: 500, msg: "没有全局配置" });
    }

    if (!themeConfig) {
        return Promise.resolve({ code: 500, msg: "模版信息错误" });
    }
    var paths = getAllFilePath(cardList, themeConfig);

    return Promise.all([createThemeCardList(cardList, themeConfig), buildThemeCss(paths, themeConfig), buildThemejs(paths, themeConfig), createThemeGlobal(global, themeConfig)]);
}

module.exports = { getCardAll, createTheme };
